// pages/mine/myOrder/orderDetail/orderDetail.js
const app = getApp(),
    globalData = app.globalData,
    api = require('../../../../api/index'),
    utils = require('../../../../utils/util'),
    pay = require('../../../../utils/pay');
Page({

    /**
     * 页面的初始数据
     */
    data: {
        orderStatus: 0, // (自) 0 待付款 1 待发货 2 待收货 3 交易成功（已收货且已评价）4 待评价(没有) 5 交易关闭（已关闭）8 申请售后中  9 申请售后成功
        // 1 待支付 2 已支付（待发货）3已发货(待收货) 4 已取消 5已完成（交易成功） 6 系统取消(交易关闭）
        pageData: {},
        id: '', // 订单id
        status: 0,
        toast: {
            visible: false,
            text: ''
        },
        imageBaseUri: globalData.imageBaseUri
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.setData({
            id: options.id || ''
        })
        console.log(options);
        this.reload();
      
    },

     reload() {
        this.getOrderDetail();
      
    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {

    },

    toLogistics() {
        wx.navigateTo({
            url: `/pages/mine/myOrder/logistics/logistics?id=${this.data.pageData.Id}`,
        })
    },

    // 获取订单详情
    async getOrderDetail() {
        try {
            let res = await api.order.orderDetail(this.data.id),
                data = res.data.ResData || {};
            console.log(res, '订单详情')
            this.setData({
                status: 2,
                pageData: data,
                orderStatus: data.Status
            })
            console.log(this.data.pageData.OrderDetailDtos[0].GoodsDto.Id,'goodid',this.data.pageData.Amount,'amount')
        //    if (this.data.pageData.DistrictAmount!=0||'0.00') {
        //        this.setData({
        //            'pageData.Amount':this.data.pageData.Amount-Number(this.data.pageData.DistrictAmount)
        //        })
        //    }
        } catch (e) {
            console.log(e, '获取订单详情失败')
            this.setData({
                status: 1
            })
        }
    },

    copy(e) {
        utils.copy(e.currentTarget.dataset.txt)
    },

    // 取消订单
    async cancelOrder() {
        let id = this.data.pageData.Id;
        try {
            let res = await api.order.cancelOrder(id);
            console.log(res, '取消订单')
            this.setData({
                toast: {
                    visible: true,
                    text: '取消订单成功'
                }
            })
            this.getOrderDetail()
        } catch (e) {
            console.log(e, '取消订单失败')
            this.setData({
                toast: {
                    visible: true,
                    text: '订单取消失败'
                }
            })
        }
    },

    // 支付订单
    async payOrder(e) {
        console.log(this.data.pageData,'订单页面支付')
        let orderInfo = this.data.pageData.OrderDetailDtos,
            obj = {},
            arr = [];

        orderInfo.forEach(item => {
            if (this.data.from == 1) {
                obj = {
                    goodsId: item.spec.GoodsId,
                    num: item.count,
                    goodsSpecId: item.spec.Id,
                    orderDoctorRequests: [
                        {
                            doctorId: this.data.docId
                        }
                    ]
                }
            } else {
                obj = {
                    goodsId: item.GoodsId,
                    num: item.Num,
                    goodsSpecId: item.Id,
                    orderDoctorRequests: [
                        {
                            doctorId: this.data.docId
                        }
                    ]
                }
            }

            arr.push(obj)
        })



        this.setData({
            filter: {
                userAddressId: this.data.pageData.UserAddressId || '',
                userCouponId: this.data.pageData.UserCouponId || '',
                remarks: this.data.pageData.Remarks || '',
                orderDetails: arr,
                orderType: 0,
                appointmentTime: "",
                deliveryTime: "",
                invitationId: wx.getStorageSync('inviteId') || ''
            },
            loading: true
        })

        if (this.data.pageData.OrderNo) {
            try {
                let res = await pay.orderPay(this.data.pageData.OrderNo)
                this.setData({
                    loading: false
                })
            } catch (e) {
                console.log(e, '取消订单')
                if (e.errMsg == 'requestPayment:fail cancel') {
                    this.setData({
                        toast: {
                            visible: true,
                            text: '支付取消'
                        },
                        loading: false
                    })
                } else {
                    this.setData({
                        toast: {
                            visible: true,
                            text: '支付失败'
                        },
                        loading: false
                    })
                }
                return
            }

            // wx.redirectTo({
            //     url: '/pages/product/paySuccess/paySuccess',
            // })
            wx.redirectTo({
                url: `/pages/product/paySuccess/paySuccess?id=${this.data.pageData.OrderDetailDtos[0].GoodsDto.Id}&sum=${this.data.pageData.Amount}`,
            })

            this.getOrderDetail()

        } else {
            this.setData({
                toast: {
                    visible: true,
                    text: '支付失败，请重试'
                }
            })
            return
        }

        console.log(res, '提交订单', this.data.filter, 'filter')

    },

    // 完成订单（确认收货）
    async completeOrder() {
        let obj={
            order_id:this.data.pageData.Id
        }
        try {
            let res = await api.order.completeOrder(obj);
            console.log(res, '确认收货');
            if (res.data.ErrCode!=0) {
                console.error(res.data.ErrMsg);
            }else{
                this.setData({
                    toast: {
                        visible: true,
                        text: '确认收货成功'
                    },
                })
            }
          
            this.getOrderDetail()

        } catch (e) {
            console.log(e, '确认收货失败')
        }
    }


})